﻿using System;
using CoreLibrary.Collection;

namespace CoreLibrary.Cache {

    public class SimpleMemoryCache : AbstractCache {
        
        private readonly ReadWriteDictionary<string, object> 
            _cache = new ReadWriteDictionary<string, object>(1000);  
        
        protected override void OnInit() {
            Asserts.NotNull(_cache, "Cache implementation must be provided.");
        }

        protected override void OnStart()  {}
        protected override void OnDestroy(){}

        protected override void OnStop() {
            if (_cache != null) {
                _cache.Clear();
            }
        }

        protected override CacheItem<T> GetItem<T>(string key) {
            var value = _cache.Get(key);
            if (value == null) {
                return new CacheItem<T>(false, default(T));
            }

            return value is T == false 
                 ? new CacheItem<T>(false, default(T)) 
                 : new CacheItem<T>(true, (T)value);
        }

        public override void Remove(string key) {
            _cache.Remove(key);
        }

        public override void Put(string key, object value) {
            _cache.Add(key, value);
        }

        public override void Put(string key, object value, TimeSpan expiration) {
            Put(key, value);
        }

    }
}